import 'package:chat_ai_demo/pages/Converstion_Page.dart';
import 'package:flutter/material.dart';
import 'package:chat_ai_demo/model/conversation_model.dart';
import 'package:chat_ai_demo/db/conversation_dao.dart';
import 'package:chat_ai_demo/db/db_manage.dart';

class ConversationListPage extends StatefulWidget {
  const ConversationListPage({super.key});

  @override
  State<ConversationListPage> createState() => _ConversationListPageState();
}

class _ConversationListPageState extends State<ConversationListPage> {
  late final ConversationListDao _conversationDao;
  final List<ConversationModel> _conversations = [];
  bool _isLoading = false;
  int _currentPage = 1;
  final int _pageSize = 20;

  @override
  void initState() {
    super.initState();
    _initDao();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _initDao() async {
    if (!mounted) return;

    try {
      final dbManager = await DBManage.instance(dbName: 'chat');
      _conversationDao = ConversationListDao(dbManager);
      await _conversationDao.ensureInitialized();

      if (!mounted) return;
      await _loadConversations();
    } catch (e) {
      print('Error initializing DAO: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('初始化数据库失败')));
      }
    }
  }

  Future<void> _loadConversations({bool refresh = false}) async {
    if (_isLoading) return;
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      if (refresh) {
        _currentPage = 1;
        _conversations.clear();
      }
    });

    try {
      final conversations = await _conversationDao.getConversationList(
        pageIndex: _currentPage,
        pageSize: _pageSize,
      );

      if (!mounted) return;
      setState(() {
        if (conversations.isNotEmpty) {
          _conversations.addAll(conversations);
          _currentPage++;
        }
      });
    } catch (e) {
      print('Error loading conversations: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('加载会话列表失败')));
      }
    } finally {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _deleteConversation(ConversationModel conversation) async {
    try {
      _conversationDao.deleteConversation(conversation);
      setState(() {
        _conversations.remove(conversation);
      });
    } catch (e) {
      print('Error deleting conversation: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('删除会话失败')));
      }
    }
  }

  Widget _buildErrorIcon(BuildContext context) {
    return const Icon(Icons.chat);
  }

  String _formatTime(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays > 7) {
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    } else if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('会话列表'),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_forever),
            onPressed: () async {
              final confirmed = await showDialog<bool>(
                context: context,
                builder:
                    (context) => AlertDialog(
                      title: const Text('确认删除'),
                      content: const Text('确定要删除所有会话吗？此操作不可恢复。'),
                      actions: [
                        TextButton(
                          onPressed: () => Navigator.pop(context, false),
                          child: const Text('取消'),
                        ),
                        TextButton(
                          onPressed: () => Navigator.pop(context, true),
                          child: const Text('确定'),
                        ),
                      ],
                    ),
              );

              if (confirmed == true && mounted) {
                try {
                  await _conversationDao.deleteAllConversations();

                  setState(() {
                    _conversations.clear();
                    _currentPage = 1;
                  });

                  if (mounted) {
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('所有会话已删除')));
                  }
                } catch (e) {
                  print('Error deleting all conversations: $e');
                  if (mounted) {
                    ScaffoldMessenger.of(
                      context,
                    ).showSnackBar(const SnackBar(content: Text('删除会话失败')));
                  }
                }
              }
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              final model = ConversationModel(
                cid: DateTime.now().millisecondsSinceEpoch,
                title: 'New Chat',
                icon:
                    'https://images.pexels.com/photos/31197867/pexels-photo-31197867.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load',
                stickTime: 0,
                updateAt: DateTime.now().millisecondsSinceEpoch,
                messageCount: 0,
                lastMessage: '',
              );

              final id = await _conversationDao.saveConversation(model);
              if (mounted && id != null) {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ConversationPage(cid: model.cid),
                  ),
                );
              }
            },
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () => _loadConversations(refresh: true),
        child:
            _isLoading && _conversations.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _conversations.isEmpty
                ? const Center(child: Text('暂无会话'))
                : ListView.builder(
                  itemCount: _conversations.length,
                  itemBuilder: (context, index) {
                    final conversation = _conversations[index];
                    return ListTile(
                      leading: CircleAvatar(
                        backgroundImage: NetworkImage(conversation.icon),
                        onBackgroundImageError:
                            (e, s) => _buildErrorIcon(context),
                      ),
                      title: Text(conversation.title),
                      subtitle: Text(
                        conversation.lastMessage ?? '',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      trailing: Text(
                        _formatTime(
                          conversation.updateAt ??
                              DateTime.now().millisecondsSinceEpoch,
                        ),
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder:
                                (context) =>
                                    ConversationPage(cid: conversation.cid),
                          ),
                        );
                      },
                    );
                  },
                ),
      ),
    );
  }
}
